package com.googlecode.wickedforms.xvergabe.modelers.fields;

import java.util.Locale;

import org.xvergabe.xsd.forms.components.x20.FieldMetaData;
import org.xvergabe.xsd.forms.components.x20.IntegerMetaData;
import org.xvergabe.xsd.forms.components.x20.RoleType;

import com.googlecode.wickedforms.model.binding.PropertyBinding;
import com.googlecode.wickedforms.model.elements.fields.TextFieldModel;
import com.googlecode.wickedforms.xvergabe.modelers.XmlModeller;
import com.googlecode.wickedforms.xvergabe.validation.MaximumValidator;
import com.googlecode.wickedforms.xvergabe.validation.MinimumValidator;
import com.googlecode.wickedforms.xvergabe.validation.PositiveNumberValidator;

public class IntegerFieldModeller
		implements
		XmlModeller<org.xvergabe.xsd.forms.components.x20.Integer, TextFieldModel<Integer>> {

	GeneralMetadataModeller metadataModeller = new GeneralMetadataModeller();

	@Override
	public TextFieldModel<Integer> createModelFromXml(
			final org.xvergabe.xsd.forms.components.x20.Integer xmlObject,
			final Locale locale, final RoleType.Enum displayMode) {

		TextFieldModel<Integer> modelfield = new TextFieldModel<Integer>( 
				Integer.class);
		modelfield.setId(xmlObject.getId());
		modelfield.setBinding(new PropertyBinding<Integer>(xmlObject, "value"));

		FieldMetaData generalMetadata = xmlObject.getMetadata();
		this.metadataModeller.addMetaDataToModel(generalMetadata, modelfield,
				locale, displayMode);

		PositiveNumberValidator<Integer> NumValidator = new PositiveNumberValidator<Integer>(
				xmlObject.getValue(), locale);
		modelfield.add(NumValidator);

		IntegerMetaData integerMetadata = xmlObject.getIntegerMetaData();

		if (integerMetadata != null && integerMetadata.isSetMin()) {
			MinimumValidator<Integer> validator = new MinimumValidator<Integer>(
					integerMetadata.getMin(), locale);
			modelfield.add(validator);
		}

		if (integerMetadata != null && integerMetadata.isSetMax()) {
			MaximumValidator<Integer> validator = new MaximumValidator<Integer>(
					integerMetadata.getMax(), locale);
			modelfield.add(validator);
		}

		if(xmlObject.isSetMetadata()){
			GeneralMetadataModeller.addMetaDataToModel(xmlObject.getMetadata(), modelfield, locale, displayMode);
		}
		
		return modelfield;
	}
}
